/**
 * 能力评估表编辑页
 */
import React, { useEffect } from 'react';
import { connect } from 'umi';
import { Form, Card, Button, Input, message, Divider } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import pageTabUtil from '@/utils/pageTabUtil';
import { useRequest } from '@/hooks';
import { FormHeader } from '@/molecules';
import { BottomAction } from '@/components';
import CancelEditConfirm from '@/components/CancelEditConfirm';
import LimitInput from '@/components/LimitInput';
import { OrganizationStrict } from '@/containers';
import { EvaluationTable, ProjectPreview, EvaluationConf } from '../containers';
import { getAbilityEvaluationDetail, saveAndUpdateAbilityEvaluation } from './services';
import styles from './index.less';

const EVALUATION_LEVEL = ['', '优秀', '良好', '合格', '需观察', '不合格'];

const EvaluationEdit = ({ form, location }) => {
    const { pathname = '', query } = location;
    const { id } = query || {};
    const { getFieldDecorator } = form;
    const [data, setData] = React.useState({});
    const [formDesc, setFormDesc] = React.useState([]);
    const [initFormValue, setInitFormValue] = React.useState({});

    // 获取能力评估表详情
    const { run: getDetail } = useRequest(aid => getAbilityEvaluationDetail(aid), {
        manual: true,
        initialData: {},
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                setData(res.data);
                const desc = (res?.data?.project || []).map((item, index) => ({
                    ...item,
                    id: item?.id || index
                }));
                setFormDesc(desc);
                return;
            }
            message.error(msg);
        }
    });

    useEffect(() => {
        if (id) {
            getDetail(id);
        }
    }, [getDetail, id]);
    const isCopyPage = React.useMemo(() => pathname.includes('add') && id, [id, pathname]);
    const evaluationRef = React.useRef();
    const [hasChanged, setHasChanged] = React.useState(false);
    const [visible, setVisible] = React.useState(false);
    const [isEditing, setIsEditing] = React.useState(false);
    const [weightError, setWeightError] = React.useState(false);

    const { loading: saveLoading, run: saveEvaluation } = useRequest(params => saveAndUpdateAbilityEvaluation(params), {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                message.success('操作成功');
                pageTabUtil.goBack();
                return;
            }
            message.error(msg);
        }
    });

    const organizationItem = form.getFieldDecorator('organizationCodeList', {
        initialValue: data?.organizationCodeList || undefined,
        rules: [
            {
                required: isCopyPage || data?.common !== 1,
                message: '适用组织机构不能为空'
            }
        ]
    })(
        <OrganizationStrict
            requestParams={{ organizationPermissions: 0, showTreeFlag: 1 }}
            placeholder="请选择组织机构"
            style={{ width: '100%' }}
            multiple
            treeCheckable
            maxTagCount={5}
            treeCheckStrictly
        />
    );

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                if (formDesc.length < 1) {
                    message.error('请添加至少一项评估项');
                    return;
                }
                const total = formDesc.reduce((prev, cur) => prev + (cur?.weight || 0), 0);
                if (total !== 100) {
                    setWeightError(true);
                    message.error('请保证总权重占比为100%');
                    return;
                }
                setWeightError(false);
                const params = {
                    ...values,
                    project: JSON.stringify(formDesc.map((item, index) => ({ ...item, id: index + 1 }))),
                    hasChanged: true
                };

                const evaluationDetail = [1, 2, 3, 4, 5]
                    .map(item => ({
                        min: values?.[`evaluationMin${item}`],
                        max: values?.[`evaluationMax${item}`],
                        level: EVALUATION_LEVEL[item],
                        entry: values?.[`entry${item}`],
                        qualified: values?.[`qualified${item}`]
                    }))
                    .filter(item => typeof item.min !== 'undefined' && typeof item.max !== 'undefined');
                Object.keys(params).forEach(c => {
                    const param = c.toString();
                    if (
                        param.startsWith('evaluationMin') ||
                        param.startsWith('evaluationMax') ||
                        param.startsWith('entry') ||
                        param.startsWith('qualified') ||
                        param.startsWith('hasChanged')
                    ) {
                        delete params[param];
                    }
                });
                params.levels = JSON.stringify(evaluationDetail);
                if (id && !isCopyPage) {
                    params.id = +id;
                }
                saveEvaluation(params);
            }
        });
    };

    React.useEffect(() => {
        if (data) {
            setInitFormValue(form.getFieldsValue());
        }
    }, [data]);
    React.useEffect(() => {
        // eslint-disable-next-line no-unused-expressions
        evaluationRef?.current?.check();
    }, []);

    const getCopyName = () => {
        if (data?.projectName?.length > 197) {
            return `${data.projectName.substring(0, 197)}-副本`;
        }
        return data?.projectName ? `${data?.projectName}-副本` : '';
    };

    return (
        <PageHeaderWrapper>
            <ProjectPreview
                visible={visible}
                onVisibleChange={setVisible}
                projectName={form.getFieldValue('projectName')}
                project={formDesc}
                projectExplain={form.getFieldValue('projectExplain')}
            />
            <Card
                title={`${id ? '编辑' : '新增'}能力评估表`}
                bordered={false}
                extra={
                    <BottomAction>
                        <CancelEditConfirm>
                            <Button
                                disabled={saveLoading}
                                onClick={e => {
                                    const hasFormChange =
                                        JSON.stringify(initFormValue) !== JSON.stringify(form.getFieldsValue());
                                    if (!hasChanged && !hasFormChange) {
                                        e.stopPropagation();
                                        pageTabUtil.goBack();
                                    }
                                }}
                            >
                                取消
                            </Button>
                        </CancelEditConfirm>
                        <Button
                            type="primary"
                            ghost
                            disabled={!!isEditing || saveLoading}
                            onClick={() => setVisible(true)}
                        >
                            预览
                        </Button>
                        <Button type="primary" loading={saveLoading} disabled={!!isEditing} onClick={handleSubmit}>
                            保存
                        </Button>
                    </BottomAction>
                }
            >
                <Form className={styles.formWrap3} style={{ maxWidth: 800, marginTop: 8 }}>
                    <Form.Item label="名称">
                        {getFieldDecorator('projectName', {
                            initialValue: isCopyPage ? getCopyName() : data?.projectName || '',
                            rules: [
                                {
                                    required: true,
                                    message: '请输入名称'
                                }
                            ]
                        })(<Input placeholder="请输入名称" allowClear maxLength={200} />)}
                    </Form.Item>
                    <Form.Item label="适用组织机构">
                        {!isCopyPage && data?.common === 1 ? '不限' : organizationItem}
                    </Form.Item>
                    <Form.Item label="每项最高分">5分</Form.Item>
                    <Form.Item label="说明" style={{ marginBottom: 0 }}>
                        {getFieldDecorator('instructions', {
                            initialValue: data?.instructions || ''
                        })(
                            <LimitInput
                                area
                                maxLength={4000}
                                placeholder="请输入说明"
                                autoSize={{ minRows: 3, maxRows: 6 }}
                            />
                        )}
                    </Form.Item>
                </Form>
                <Divider />
                <FormHeader title="评估细项信息" style={{ margin: '32px 0 24px' }} />
                <div style={{ maxWidth: 1080 }}>
                    <EvaluationConf form={form} ref={evaluationRef} data={data} className={styles.formWrap} />
                    <EvaluationTable
                        dataSource={formDesc}
                        weightError={weightError}
                        onChange={arr => {
                            if (!hasChanged && JSON.stringify(arr) !== JSON.stringify(formDesc)) {
                                setHasChanged(true);
                            }
                            setFormDesc(arr);
                        }}
                        onEditing={setIsEditing}
                    />
                </div>
            </Card>
        </PageHeaderWrapper>
    );
};

export default connect(() => ({}))(Form.create({})(EvaluationEdit));
